package neu.soft.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import neu.soft.constant.PayableOrderType;
import neu.soft.entity.PayableOrder;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.facade.PurchasePayHandler;
import neu.soft.query.PayableOrderQuery;
import neu.soft.service.PayableOrderService;
import neu.soft.vo.PageBean;
import neu.soft.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/payable")
@CrossOrigin
@Slf4j
public class PayableOrderController {

    @Autowired
    PayableOrderService payableOrderService;

    @Autowired
    PurchasePayHandler purchasePayHandler;


    @SneakyThrows
    @PostMapping
    public ResultBean<PageBean<PayableOrder>> findByPage(@RequestBody PayableOrderQuery payableOrderQuery){
        PageBean<PayableOrder> pageBean = payableOrderService.findByPage(payableOrderQuery);
        return ResultBean.success(pageBean);
    }

    @PostMapping("/pay")
    public ResultBean pay(@RequestBody Map<String, Object> map){

        List<String> payableOrderId = (List<String>) map.get("payableOrderId");
//        得到Long类型的id
        List<Long> idCollect = payableOrderId.stream().map(Long::valueOf).collect(Collectors.toList());
        //批量查询应付单
        List<PayableOrder> payableOrderList = payableOrderService.batchFindPayableOrder(idCollect);
        for (PayableOrder payableOrder:payableOrderList
             ) {
            if ("0".equals(payableOrder.getPayType())){
                throw new AppException(AppExceptionCodeMsg.REPEAT_FAIL);
            }
            purchasePayHandler.payPurchaseOrder(payableOrder);
            //更新应付单类型
            payableOrder.setPayType(PayableOrderType.PAID.getCode());
        }
        payableOrderService.update(payableOrderList);
        return ResultBean.success();

    }
    
}
